package com.kzd.gtboon.main.game

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.*
import android.webkit.WebView
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.ConvertUtils
import com.kzd.gtboon.R
import com.kzd.gtboon.app.URL_GAME_H5
import com.kzd.gtboon.app.SPSConstance
import com.kzd.gtboon.callback.AppWebViewClient
import com.kzd.gtboon.jetpack.vm.GameViewModel
import com.kzd.gtboon.main.*
import com.kzd.gtboon.main.popup.SystemTipsPopup
import com.kzd.gtboon.main.web.WebViewActivity
import com.kzd.gtboon.utils.httpSign1
import com.kzd.gtboon.utils.httpTime
import com.module.lemlin.http.Status
import com.module.lemlin.image.loadCircleImage
import com.module.lemlin.owner.ownerViewModel

class GameH5Activity : WebViewActivity() {

    private var mGameId: String? = null
    private var mGameName: String? = null
    private var mGameIcon: String? = null

    private val mWindowManager: WindowManager by lazy {
        getSystemService(WINDOW_SERVICE) as WindowManager
    }

    private val mLayoutParams: WindowManager.LayoutParams by lazy {
        WindowManager.LayoutParams().apply {
            type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
            format = PixelFormat.RGBA_8888
            gravity = Gravity.TOP or Gravity.END
            flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            width = WindowManager.LayoutParams.WRAP_CONTENT
            height = ConvertUtils.dp2px((45f))
            y = ConvertUtils.dp2px((70f))
        }
    }

    private val mFloatingView: View by lazy {
        LayoutInflater.from(this as Context).inflate(R.layout.view_service_floating, (null))
    }

    private val mAppWebViewClient = object : AppWebViewClient() {
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            val gid = Uri.parse(url).getQueryParameter("gid")
                ?: return
            if (mGameId == gid) {
                return
            }
            mViewModel.gameDetails(gid)
        }

    }

    private val mSystemTipsPopup: SystemTipsPopup by lazy {
        SystemTipsPopup(context = this) {
            if (it.id == R.id.tvSystemTipsClose) {
                finish()
            } else if (it.id == R.id.tvSystemTipsSure && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val intent = Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse(("package:$packageName"))
                )
                startActivityForResult(intent, (0))
            }
        }
    }

    private val mViewModel:GameViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override fun initView() {
        super.initView()
        mWebView.webViewClient = mAppWebViewClient
    }

    override fun initData() {
        mGameId = intent?.extras?.getString(KEY_GAME_ID)
        mGameName = intent?.extras?.getString(KEY_GAME_TITLE)
        mGameIcon = intent?.extras?.getString(KEY_GAME_ICON)

        mWebView.loadUrl(httpUrl(mGameId))
    }

    override fun initViewMode() {
        mViewModel.gameDetailsLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            mGameId = data.id
            mGameName = data.name
            mGameIcon = data.icon
        })
    }

    override fun onResume() {
        super.onResume()
        closeFloatingWindow()
    }

    override fun onPause() {
        super.onPause()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(this as Context)) {
            showFloatingWindow()
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val gameId = intent?.extras?.getString(KEY_GAME_ID)
        if (mGameId != gameId) {
            mWebView.loadUrl(httpUrl(gameId))
        }
        mGameId = gameId
        mGameName = intent?.extras?.getString(KEY_GAME_TITLE)
        mGameIcon = intent?.extras?.getString(KEY_GAME_ICON)
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this as Context)) {
                mSystemTipsPopup.setMessage("是否开启悬浮窗口？")
                    .setButtonText(sure = "去开启", close = "直接退出")
                    .setVisibleClose()
                    .showPopupWindow()
            } else {
                moveTaskToBack(true)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        closeFloatingWindow()
        super.onDestroy()
    }

    private fun httpUrl(gid: String?): String {
        val uid = SPSConstance.uid ?: ""
        val url = StringBuilder(URL_GAME_H5)
            .append("&uid=").append(uid)
            .append("&gid=").append(gid)
            .append("&t=").append(httpTime)
            .append("&sign=").append(httpSign1(uid))
            .append("&type=").append("1")
        return url.toString()
    }

    private fun showFloatingWindow() {
        mFloatingView.setOnClickListener {
            toGameH5Activity(mGameName, mGameIcon, mGameId)
        }
        mFloatingView.findViewById<ImageView>(R.id.ivFloatingClose)
            .setOnClickListener { finish() }
        mFloatingView.findViewById<TextView>(R.id.tvFloatingName)
            .text = mGameName
        mFloatingView.findViewById<ImageView>(R.id.ivFloatingIcon)
            .loadCircleImage(
                src = mGameIcon ?: R.mipmap.ic_80008,
                R.mipmap.ic_80008, R.mipmap.ic_80008
            )
        if (mFloatingView.windowToken != null) {
            mWindowManager.updateViewLayout(mFloatingView, mLayoutParams)
        } else {
            mWindowManager.addView(mFloatingView, mLayoutParams)
        }
    }

    private fun closeFloatingWindow() {
        if (mFloatingView.windowToken != null) {
            mWindowManager.removeView(mFloatingView)
        }

    }

}
